package com.sun.controller;

import com.github.pagehelper.PageInfo;
import com.sun.enums.HttpEnum;
import com.sun.pojo.dto.UsersDto;
import com.sun.pojo.entity.Users;
import com.sun.pojo.vo.R;
import com.sun.service.UsersService;
import com.sun.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author SunRui
 * @description 控制层
 * @date 2024/10/17 8:44
 */
@RestController
@RequestMapping("users")
@CrossOrigin
public class UsersController {

    @Autowired
    UsersService usersService;

    // 根据 ID、姓名、性别、邮箱 分别查询用户信息
    @GetMapping
    public R<PageInfo<Users>> selectUsersBy(UsersDto usersDto, Integer pageNum) {
        PageInfo<Users> usersPageInfo;
        usersPageInfo = usersService.selectUsersBy(usersDto, pageNum);
        return R.success(usersPageInfo);
    }

    // 新增用户
    @PostMapping
    public R<String> addUsers(@Valid Users users, MultipartFile imageFile, HttpServletRequest request) {
        users.setStatus(1);
        String imagePath;
        try {
            imagePath = FileUtil.upload(request, imageFile);
            if (imagePath != null) {
                users.setImagePath(imagePath);
                if (usersService.addUsers(users) > 0) {
                    return R.success("新增用户成功");
                }
            }
        } catch (Exception e) {
            return R.fail(HttpEnum.ERROR.getCode(), e.getMessage());
        }
        return R.fail(HttpEnum.WARN.getCode(), "新增失败");
    }

    // 修改用户信息
    @PostMapping("update")
    public R<String> updateUsers(@Valid Users users, MultipartFile imageFile, HttpServletRequest request) {
        String imagePath;
        try {
            imagePath = FileUtil.upload(request, imageFile);
            if (imagePath != null) {
                users.setImagePath(imagePath);
            }else {
                String imagePath1 = usersService.selectImagePath(users.getId());
                users.setImagePath(imagePath1);
            }
            if (usersService.updateUsers(users) > 0) {
                return R.success("修改用户成功");
            }
        } catch (Exception e) {
            return R.fail(HttpEnum.ERROR.getCode(), e.getMessage());
        }
        return R.fail(HttpEnum.WARN.getCode(), "修改失败");
    }

    // 通过ID 修改用户状态进行禁用
    @PutMapping("/{id}/{status}")
    public R<String> deleteUsers(@PathVariable("id") Integer id, @PathVariable("status") Integer status) {
        if (usersService.deleteUsers(id, status) > 0) {
            return R.success("禁用成功");
        } else {
            return R.fail(HttpEnum.WARN.getCode(), "禁用失败");
        }
    }

}
